{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ctypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 基本用法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`ctypes` 是一个方便 `Python` 调用本地已经编译好的外部库的模块。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from ctypes import util, CDLL"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 标准 C 库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `util` 来找到标准 `C` 库："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "msvcr90.dll\n"
     ]
    }
   ],
   "source": [
    "libc_name = util.find_library('c')\n",
    "\n",
    "# on WINDOWS\n",
    "print libc_name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `CDLL` 来加载 `C` 库："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "libc = CDLL(libc_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "libc 包含 `C` 标准库中的函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<_FuncPtr object at 0x0000000003CEE048>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "libc.printf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调用这个函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "libc.printf(\"%s, %d\\n\", \"hello\", 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里显示的 `9` 是 `printf` 的返回值表示显示的字符串的长度（包括结尾的 `'\\0'`），但是并没有显示结果，原因是 `printf` 函数默认是写在标准输出流上的，与 `IPython` 使用的输出流不一样，所以没有显示结果。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## C 数学库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "找到数学库："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "msvcr90.dll\n"
     ]
    }
   ],
   "source": [
    "libm_name = util.find_library('m')\n",
    "\n",
    "print libm_name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调用 `atan2` 函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "ArgumentError",
     "evalue": "argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mArgumentError\u001b[0m                             Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-7-e784e41ee9f3>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mlibm\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mCDLL\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlibm_name\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mlibm\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0matan2\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1.0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2.0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mArgumentError\u001b[0m: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1"
     ]
    }
   ],
   "source": [
    "libm = CDLL(libm_name)\n",
    "\n",
    "libm.atan2(1.0, 2.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调用这个函数出错，原因是我们需要进行一些额外工作，告诉 `Python` 函数的参数和返回值是什么样的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from ctypes import c_double\n",
    "\n",
    "libm.atan2.argtypes = [c_double, c_double]\n",
    "libm.atan2.restype = c_double"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.4636476090008061"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "libm.atan2(1.0, 2.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "与 `Python` 数学库中的结果一致："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from math import atan2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.4636476090008061"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "atan2(1.0, 2.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Numpy 和 ctypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "假设我们有这样的一个函数：\n",
    "```c\n",
    "float _sum(float *vec, int len) {\n",
    "    float sum = 0.0;\n",
    "    int i;\n",
    "    for (i = 0; i < len; i++) {\n",
    "        sum += vec[i];\n",
    "    }\n",
    "    return sum\n",
    "}\n",
    "```\n",
    "\n",
    "并且已经编译成动态链接库，那么我们可以这样调用：\n",
    "\n",
    "```python\n",
    "from ctypes import c_float, CDLL, c_int\n",
    "from numpy import array, float32\n",
    "from numpy.ctypeslib import ndpointer\n",
    "\n",
    "x = array([1,2,3,4], dtype=float32)\n",
    "\n",
    "lib = CDLL(<path>)\n",
    "\n",
    "ptr = ndpointer(float32, ndim=1, flags='C')\n",
    "lib._sum.argtypes = [ptr, c_int]\n",
    "lib._sum.restype = c_float\n",
    "\n",
    "result = lib._sum(x, len(x))\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
